package com.rzico.sbl.ui.statistic

import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityStockCheckBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.model.StockGoods
import com.rzico.sbl.viewmodel.StatisticStockViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.listener._TextWatcher
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.abs

class StockCheckActivity : BaseActivity(R.layout.activity_stock_check) {

    private val mBinding by lazy { ActivityStockCheckBinding.bind(getRootView()) }

    private val mShopList = arrayListOf<FilterData>()
    private var mShopId = ""

    override fun getViewModel() = get<StatisticStockViewModel>()

    override fun initData() {
        initTitle(title = "库存盘点")

        initLayout()

        getShopList()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .emptyHint
                    .text = "暂无相关商品信息！"

                swipeRefresh.isEnabled = false

                recycleList.also { layout ->
                    layout.loadLinear(
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                    mAdapter = SlimAdapter.creator()
                        .register<StockGoods>(R.layout.item_stock_check) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_stock_name, bean.name)
                                text(R.id.item_stock_code, bean.sn)
                                text(R.id.item_stock_group, bean.mapProductCategory?.name.orEmpty())
                                text(R.id.item_stock_stock, bean.stock)
                                text(
                                    R.id.item_stock_diff,
                                    abs(bean.stock.intValue - bean.realStock.intValue).toString()
                                )

                                visibility(
                                    R.id.item_stock_diff_ll,
                                    visibleValue { bean.stock.intValue != bean.realStock.intValue }
                                )

                                with<ImageView>(R.id.item_stock_img) {
                                    it.loadImage(bean.thumbnail)
                                }

                                with<EditText>(R.id.item_stock_input) {
                                    if (it.tag != null && it.tag is TextWatcher) {
                                        it.removeTextChangedListener(it.tag as TextWatcher)
                                    }

                                    it.setText(bean.realStock)
                                    it.setSelection(it.text.length)

                                    val textWatcher = object : _TextWatcher() {
                                        override fun afterTextChanged(s: Editable) {
                                            bean.realStock = s.toString()

                                            val before = bean.stock.intValue
                                            val after = bean.realStock.intValue
                                            getView<TextView>(R.id.item_stock_diff)
                                                .text = abs(before - after).toString()
                                            getView<View>(R.id.item_stock_diff_ll)
                                                .isVisible = before != after
                                        }
                                    }
                                    it.addTextChangedListener(textWatcher)
                                    it.tag = textWatcher
                                }

                                clicked(R.id.item_stock_sync) {
                                    syncStock(getView(R.id.item_stock_sync), bean, index)
                                }

                                clicked {
                                    startActivityEx<StockRecordActivity>(
                                        "stockId" to bean.id
                                    )
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    override fun initListener() {
        mBinding
            .goodsShop
            .apply {
                timeHint.text = "仓库名称"

                timeLayout
                    .oneClick {
                        getViewModel()
                            .showDropTimeFilter(
                                getIContext(),
                                timeHint,
                                timeHintArrow,
                                timeLayout,
                                mShopList
                            ) { bean ->
                                mShopId = bean.id

                                updateList()
                            }
                    }
            }
    }

    /**
     * 库存盘点修正
     */
    private fun syncStock(anchor: View, bean: StockGoods, index: Int) {
        showHintDialog(
            hint = "确定要同步实际修改库存吗？",
            onSure = {
                val before = bean.stock.intValue
                val after = bean.realStock.intValue

                getViewModel()
                    .requestBind(
                        isLoading = false,
                        isMultipart = true,
                        requestUrl = BaseUrl.psiStock,
                        params = arrayOf(
                            "id" to bean.id,
                            "action" to conditionIf(before < after, 0, 1),
                            "quantity" to abs(before - after),
                            "subject" to conditionIf(before < after, "手动入库", "手动出库"),
                            "memo" to "APP库存盘点修正"
                        ),
                        onBefore = {
                            anchor.startAnimation(
                                AnimationUtils
                                    .loadAnimation(
                                        getIContext(),
                                        R.anim.anim_rotate
                                    )
                            )
                        },
                        onAfter = { anchor.clearAnimation() }
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("同步成功！")

                            bean.stock = bean.realStock
                            mAdapter.notifyItemChanged(index)
                        }
                    )
            }
        )
    }

    /**
     * 获取店铺列表，含自提点
     */
    private fun getShopList() {
        getViewModel()
            .shopList(
                onSuccess = { list ->
                    mShopList.clear()
                    list.notEmpty {
                        mapTo(mShopList) {
                            FilterData(
                                it.shopName.orEmpty(),
                                it.id,
                                it.shopName.orEmpty()
                            )
                        }
                    }

                    mShopId = mShopList[0].id
                    mShopList[0].isChecked = true

                    mBinding.apply {
                        goodsShop
                            .timeHint
                            .text = mShopList[0].name
                    }
                },
                onFinally = {
                    lifecycleScope.launch {
                        delay(200)
                        getData(pageNum)
                    }
                }
            )
    }

    /**
     * 商品列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodsList(
                page = index,
                shopId = mShopId,
                keyWord = "",
                isLoading = true,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it.data)
                        it.data.notEmpty { pageNum++ }
                    }

                    mList.forEach {
                        it as StockGoods
                        it.realStock = it.stock
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .emptyLayout
                        .emptyView
                        .isVisible = mList.isEmpty()
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .emptyLayout
            .emptyView
            .gone()

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}